<template>
  <div class="app-container">
    <div class="app-title">
      <span>单位信息编辑</span>
    </div>
    <!-- 切换按钮 -->
    <el-row :gutter="20">
      <el-col :span="8">
        <el-col :span="1">
          <i :class="[treeShow ? 'el-icon-s-fold treeI': 'el-icon-s-unfold treeI']" @click="toggerTree" />
        </el-col>
      </el-col>
      <div class="filter-container">
        <div>
          <el-col
            style="text-align:right;margin-top: -8px;"
            :span="16"
          >
            <el-button
              size="small"
              class="filter-item"
              style="margin-left: 10px;"
              type="primary"
              @click="handleEdit"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              class="filter-item"
              type="primary"
              @click="handleView"
            >
              预览
            </el-button>
            <el-button
              size="small"
              class="filter-item"
              style="margin-left: 10px;"
              type="primary"
              @click="appendixOpen"
            >
              附件管理
            </el-button>
          </el-col>
        </div>
      </div>
    </el-row>

    <div class="grid-content bg-purple" />

    <div
      ref="box"
      class="box"
    >
      <div
        class="left"
        :class="[isActive ? 'wid':'wids']"
      >
        <div
          :class="[treeShow ? 'treeShow' : 'treeNotShow']"
          :style="{'height' : treeHeight + 'px'}"
        >
          <AgencyTree
            class="agencyTree"
            @handleTreeQuery="handleTreeQuery"
          />
        </div>
      </div>
      <div
        v-show="Show"
        class="resize"
        title="收缩侧边栏"
      />
      <div
        class="mid"
        :class="[isActive ? 'mids': 'min']"
      >
        <!-- 表格部分 -->
        <el-table
          ref="singalTable"
          v-loading="listLoading"
          :height="tableHeight"
          :data="list"
          :stripe="true"
          fit
          :header-cell-style="{background:'#eef1f6',color:'#606266'}"
          @cell-dblclick="editclick"
        >
          <template slot="empty">
            <tableEmpty />
          </template>
          <el-table-column type="selection" align="center" width="50" label="序号" />
          <el-table-column type="index" align="center" width="50" label="序号" />
          <el-table-column label="操作日期" align="center">
            <template slot-scope="{row}">
              <span>{{ row.updateTime | parseTime('{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单位代码" align="center">
            <template slot-scope="{row}">
              <span style="float: left">{{ row.agencyCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单位名称" align="center">
            <template slot-scope="{row}">
              <span style="float: left">{{ row.agencyName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="发卡银行" align="center">
            <template slot-scope="{row}">
              <!-- | bankFilters(that)  -->
              <span>{{ row.agencyBankName }}</span>
            </template>
          </el-table-column>
           <el-table-column label="是否生成支付" align="center">
            <template slot-scope="{row}">
              <!-- | bankFilters(that)  -->
              <span>{{row.isPaymentAgency | verifyFilter(that)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="是否允许上报" align="center">
            <template slot-scope="{row}">
              <!-- | bankFilters(that)  -->
              <span>{{row.isSubmitAble | submitFilter(that)}}</span>
            </template>
          </el-table-column>
           <el-table-column label="是否停用" align="center">
            <template slot-scope="{row}">
              <!-- | bankFilters(that)  -->
              <span>{{row.isDeleted | deletedFilter(that)}}</span>
            </template>
          </el-table-column>
             <el-table-column label="备注" align="center">
            <template slot-scope="{row}">
              <span style="float: left">{{ row.remarks }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
      </div>
      <Drag ref="icon" />

    </div>
    <!-- 编辑页面部分 -->
    <el-dialog  v-dialogDrag  
      :close-on-click-modal="false"
      :title="dialogStatus"
      :visible.sync="dialogEditFormVisible"
      width="20%"
    >
      <el-form
        ref="dataForm"
        class="dialog-backgroundcolor"
        :rules="dataFormRules"
        :model="formData"
        label-position="right"
        label-width="100px"
      >
        <div class="editFormDeviation">
          <el-row>
            <el-col>
              <el-form-item
                label="单位代码："
                prop="agencyCode"
                class="item-margin"
              />
            </el-col>
            <el-col>
              <el-input
                v-model="formData.agencyCode"
                disabled
              />
            </el-col>
          </el-row>

          <el-row>
            <el-col>
              <el-form-item
                label="单位名称："
                prop="agencyName"
                class="item-margin"
              />
            </el-col>
            <el-col>
              <el-input
                v-model="formData.agencyName"
                disabled
              />
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item
                label="发卡银行："
                prop="agencyBankName"
                class="item-margin"
              />
            </el-col>
            <el-col>
              <el-select
                v-model="formData.agencyBankNames"
                value-key="code"
                multiple
                class="filter-item"
                placeholder="--请选择--"
              >
                <el-option
                  v-for="item in agencyBankLists"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-col>
          </el-row>
           <el-row>
            <el-col class='payment'>
              <el-form-item
                label="是否生成支付:"
                prop="isPaymentAgency"
                class="item-margin"
              />
            </el-col>
            <el-select v-model="formData.isPaymentAgency " 
              class="filter-item"
              placeholder="--请选择!--">
             <el-option
                      label="是"
                      value="1"
                    />
                    <el-option
                      label="否"
                      value="0"
                    />
            </el-select>
          </el-row>

          <el-row>
            <el-col>
              <el-form-item
                label="是否允许上报:"
                prop="isSubmitAble"
                class="item-margin"
                 style="margin-left: -3px;"
              />
            </el-col>
            <el-select v-model="formData.isSubmitAble " 
              class="filter-item"
              placeholder="--请选择是否允许!--">
              <el-option
                  v-for="item in isSubmitAbles"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
            </el-select>
          </el-row>

            <el-row>
            <el-col>
              <el-form-item
                label="是否停用:"
                prop="isDeleted"
                class="item-margin"
                 style="margin-left: -31px;"
              />
            </el-col>
            <el-select v-model="formData.isDeleted " 
              class="filter-item"
              placeholder="--请选择是否停用!--">
              <el-option
                  v-for="item in isDeleteds"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
            </el-select>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item
                label="备注："
                prop="remarks"
                class="item-margin"
                 style="margin-left: -49px;"
              />
            </el-col>
            <el-col >
              <el-input
                v-model="formData.remarks"
               
              />
            </el-col>
          </el-row>
        </div>
        <el-row>
          <el-col
            v-if="operate === 'edit'"
            style="text-align: center; margin-top:20px; margin-bottom:8px"
          >
            <el-button
              type="primary"
              :loading="saveLoading"
              @click="updateData()"
            >
              保存
            </el-button>
            <el-button @click="dialogEditFormVisible = false">
              取消
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
    <!-- 查看页面部分 -->
    <el-dialog  v-dialogDrag  
      :close-on-click-modal="false"
      :title="dialogStatus"
      :visible.sync="viewFormVisible"
      width="55%"
    >
      <el-form
        ref="dataForm"
        class="dialog-backgroundcolor"
        :model="formData"
        label-position="right"
        disabled
        size="small"
      >
        <div class="viewFormDeviation">
          <el-row>
            <el-col :span="8">
              <el-form-item
                label="单位代码："
                prop="agencyCode"
              />
              <el-input
                v-model="formData.agencyCode"
                disabled
              />
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="单位名称："
                prop="agencyName"
              />
              <el-input
                v-model="formData.agencyName"
                disabled
              />
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="单位简称："
                prop="agencyAbbreviation"
              />
              <el-input
                v-model="formData.agencyAbbreviation"
                disabled
              />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item
                label="财政区划："
                prop="mofDivCode"
              />
              <el-select
                v-model="formData.mofDivCode"
                class="filter-item"
                placeholder="--请选择--"
                disabled
              >
                <el-option
                  v-for="item in mofDivLists"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="统一社会信用代码："
                prop="unifsocCredCode"
              />
              <el-input
                v-model="formData.unifsocCredCode"
                disabled
              />
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="单位地址："
                prop="agencyAddress"
              />
              <el-input
                v-model="formData.agencyAddress"
                disabled
              />
            </el-col>
          </el-row>
          <el-row>

            <el-col :span="8">
              <el-form-item
                label="邮政编码："
                prop="zip"
              />
              <el-input
                v-model="formData.zip"
                disabled
              />
            </el-col>
            <!-- <el-col :span="8">
              <el-form-item
                label="是否末级："
                prop="isLeaf"
              />
              <el-select
                v-model="formData.isLeaf"
                class="filter-item"
                placeholder="--请选择--"
                disabled
              >
                <el-option
                  label="是"
                  :value="1"
                />
                <el-option
                  label="否"
                  :value="0"
                />
              </el-select>
            </el-col> -->
            <el-col :span="8">
              <el-form-item
                label="单位类型："
                prop="agencyType"
              />
              <el-select
                v-model="formData.agencyType"
                class="filter-item"
                placeholder="--请选择--"
                disabled
              >
                <el-option
                  v-for="item in AgencyAdmdepLists"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="单位负责人："
                prop="agencyLeader"
              />
              <el-input
                v-model="formData.agencyLeader"
                disabled
              />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item
                label="行政级别："
                prop="agencyAdmLevelCode"
              />
              <el-select
                v-model="formData.agencyAdmLevelCode"
                class="filter-item"
                placeholder="--请选择--"
                disabled
              >
                <el-option
                  v-for="item in AgencyadmlevelLists"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="发卡银行："
                prop="agencyBankNames"
              />
              <el-select
                v-model="formData.agencyBankNames"
                multiple
                class="filter-item"
                placeholder="--请选择--"
              >
                <el-option
                  v-for="item in agencyBankLists"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="备注："
                prop="remarks"

              />
              <el-input
                v-model="formData.remarks"
              />
            </el-col>
          </el-row>
        </div>
      </el-form>
    </el-dialog>
    <Enclosure
      ref="enc"
      :middle-table-code="1"
    />
  </div>
</template>
<script>
import { getAgencyList, updateAgencyInfoAudit ,agencyPerson} from '@/api/unitInformationMaintenance/unitInformationEdit'
import { getAgencyBank, getAgencyMofDiv, getAgencyAdmdep, getAgencyAgencyadmlevel } from '@/api/baseInfo'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import tableEmpty from '@/components/table/empty'
import Enclosure from '@/components/Enclosure'
import AgencyTree from '@/components/tree/agencyTree'
import Drag from '@/components/Drag'
export default {
  name: 'Unit',
  components: { Pagination, tableEmpty, Enclosure, AgencyTree, Drag },
  filters: {
    bankFilters(type, that) {
      const agencyBankLists = that.agencyBankLists
      for (const item in agencyBankLists) {
        if (agencyBankLists[item].code === type) {
          return agencyBankLists[item].name
        }
      }
    },
     verifyFilter(value, that) {
      if (value === '0') {
        return '否'
      }
      if (value === '1'|| value === '' ) {
        return '是'
      }
      return value
    },
      submitFilter(value, that) {
      if (value === 1 || value === null ) {
        return '允许上报'
      }
      if (value === 0) {
        return '不允许上报'
      }
      return value
    },

      deletedFilter(value, that) {
      if (value === 0) {
        return '否'
      }
      if (value === 1||  value === '' ) {
        return '是'
      }
      return value
    }
  },
  data() {
    return {
      isDeleteds:[
        {value:1,label:"是"},
        {value:0,label:"否"}
      ],
      isSubmitAbles:[
        {value:0,label:"不允许上报"},
        {value:1,label:"允许上报"},
      ],
      treeHeight: null,
      isActive: true,
      Show: false,
      treeShow: false,
      treeData: '',
      tableHeight: null,
      selection: [],
      that: this,
      list: null,
      total: 0,
      listLoading: true,
      saveLoading: false,
      listQuery: {
        page: 1,
        limit: 200,
        flag: 'all',
        agencyId: '0'
      },
      formDsiabled: false,
      operate: 'edit',
      mofDivLists: [],
      agencyBankLists: [],
      AgencyAdmdepLists: [],
      AgencyadmlevelLists: [],
      formData: {
        id: '',
        agencyCode: '',
        agencyName: '',
        agencyAbbreviation: '',
        mofDivCode: '',
        unifsocCredCode: '',
        isLeaf: '',
        agencyType: '',
        adminCardNum: '',
        causeCardNum: '',
        retirementCardNum: '',
        centralAgencyCode: '',
        agencyAddress: '',
        zip: '',
        agencyLeader: '',
        agencyAdmLevelCode: '',
        agencyBankNames: null,
        isPaymentAgency: '',
        isUniSala: '',
        remarks: '',
        isDeleted: '',
        isSubmitAble: ''
      },
      viewFormData: {
        agency_code: '', // 单位编码
        agency_name: '', // 单位名称
        agency_abbreviation: '', // 单位简称
        mof_div_code: '', // 财政区划
        unifsoc_cred_code: '', //  统一信用代码
        agency_add: '', // 单位地址
        zip: '', //  邮编
        is_leaf: '', // 是否末级
        agency_type_code: '', // 单位类型
        agency_leader_per_name: '', // 单位负责人
        agency_adm_level_code: '', // 行政级别
        agencyBankNames: null,
        remarks: ''
      },
      operateAgencyLists: [],
      dialogEditFormVisible: false,
      viewFormVisible: false,
      dialogStatus: '',
      dataFormRules: {
        agencyCode: [
          { required: true, message: '请输入单位代码', trigger: 'blur' }
        ],
        agencyName: [
          { required: true, message: '请输入单位名称', trigger: 'blur' }
        ],
        unifsocCredCode: [
          { required: true, message: '请输入统一社会信用代码', trigger: 'blur' }
        ],
        agencyType: [
          { required: true, message: '请输入单位类型', trigger: 'blur' }
        ],
        centralAgencyCode: [
          { required: true, message: '请输入归口处室', trigger: 'blur' }
        ],
        agencyLeader: [
          { required: true, message: '请输入单位负责人', trigger: 'blur' }
        ],
        isUniSala: [
          { required: true, message: '请输入是否统发', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    // 表格的数据数组
    list(val) {
      this.doLayout()
    }
  },
  created() {
    this.initBaseInfo()
    this.getList()
  },
  mounted() {
    this.getTbHeight()
    this.dragController()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
  },
  methods: {
    // 拖拽
    dragController() {
      this.$refs.icon.dragControllerDiv()
    },
    toggerTree() {
      this.treeShow = !this.treeShow
      this.isActive = !this.isActive
      this.Show = !this.Show
    },
    handleTreeQuery(data) {
      this.treeData = data
      this.handleTree(data)
    },
    /* 重新渲染table组件 */
    doLayout() {
      this.$nextTick(() => {
        this.$refs.singalTable.doLayout()
      })
    },
    // 获取table高度的方法
    getTbHeight() {
      this.tableHeight = window.innerHeight - 215
      this.treeHeight = this.tableHeight
    },
    editclick(row, column, event, cell) {
      this.dialogStatus = '单位基本信息'
      this.dialogEditFormVisible = true
      this.formData = row
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    getList() {
      this.listLoading = true
      getAgencyList(this.listQuery).then(response => {
        const rows = response.data.rows
        rows.forEach(item => {
          if (item.agencyBankName !== '' && item.agencyBankName !== null) {
            // 编辑页面显示银行
            const agencyBankName = []
            // 列表显示银行
            let agencyTableBankName = ''
            // 获取返回的银行，获取code
            let bankName = item.agencyBankName
            bankName = bankName.substring(1, bankName.length - 1)
            const bankNames = bankName.split(',')
            // 将code放到编辑页面银行的数组中，
            // table显示的银行需要将code转为name后，存到列表数据中
            for (let i = 0; i < bankNames.length; i++) {
              agencyBankName.push(bankNames[i])
              for (const item in this.agencyBankLists) {
                if (this.agencyBankLists[item].code === bankNames[i]) {
                  agencyTableBankName += this.agencyBankLists[item].name + '，'
                }
              }
            }
            item.agencyBankName = agencyTableBankName.substring(0, agencyTableBankName.length - 1)
            item.agencyBankNames = agencyBankName
          }
        })
        this.list = rows
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleTree(data) {
      this.listQuery.agencyId = data.id
      this.getList()
      // if (!Object.prototype.hasOwnProperty.call(data, 'children')) {
      // }
    },
    // 编辑
    handleEdit() {
      const selection = this.$refs.singalTable.selection
      if (selection.length !== 1) {
        this.$message({
          showClose: true,
          message: '请选择要修改的单位',
          type: 'warning',
          duration: 4000
        })
        return
      }
      this.dialogStatus = '单位基本信息'
      this.dialogEditFormVisible = true
      this.formData = Object.assign({}, this.formData, selection[0])
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 保存
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.saveLoading = true
          const tempData = Object.assign({}, this.formData)
          agencyPerson(tempData.id).then((res)=>{
              if(tempData.isDeleted =='1'){
                 if (res.data > 0) {
                this.$message({
                message: "单位存在人员不允许停用",
                type: "warning",
                showClose: true,
                duration: 4000,
                });
                this.saveLoading = false
                  return
                  }
               }
          updateAgencyInfoAudit(tempData).then((response) => {
            this.dialogEditFormVisible = false
            this.$message({
              showClose: true,
              message: '保存成功',
              type: 'success',
              duration: 4000
            })
            this.saveLoading = false
            this.handleFilter()
          }).catch(() => {
            this.saveLoading = false
          })
          }).catch(() => {
            this.saveLoading = false
          })
        }
      })
    },
    // 预览
    handleView() {
      const selection = this.$refs.singalTable.selection
      if (selection.length !== 1) {
        this.$message({
          showClose: true,
          message: '请选择要预览的单位',
          type: 'warning',
          duration: 4000
        })
        return
      }
      this.viewFormData = []
      this.dialogStatus = '单位基本信息'
      this.viewFormVisible = true
      this.formData = Object.assign({}, this.formData, selection[0])
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      // const param = { agencyId: selection[0].id }
      // getAgencyInfo(param).then((response) => {
      //   this.viewFormData = Object.assign({}, this.viewFormData, response.data[0])
      //   this.viewFormData.agencyBankNames = selection[0].agencyBankNames
      // })
    },
    // 附件方法
    appendixOpen() {
      this.selection = this.$refs.singalTable.selection
      if (this.selection.length !== 1) {
        this.$message({
          showClose: true,
          message: '请选择一条数据',
          type: 'warning',
          duration: 4000
        })
        return
      }
       this.selection.forEach(item => {
        this.agencyId = item.id
      })
      this.$refs.enc.appendixOpen(this.selection, true, '单位名称',this.agencyId,1)
    },
    initBaseInfo() {
      getAgencyAdmdep().then((response) => {
        this.AgencyAdmdepLists = Object.assign({}, response.data)
      })
      getAgencyAgencyadmlevel().then((response) => {
        this.AgencyadmlevelLists = Object.assign({}, response.data)
      })
      getAgencyBank().then((response) => {
        this.agencyBankLists = Object.assign({}, response.data)
      })
      getAgencyMofDiv().then((response) => {
        this.mofDivLists = Object.assign({}, response.data)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .editFormDeviation {
    margin-left: 10%;
  }
  .viewFormDeviation {
    margin-left: 6%;
  }
  ::v-deep .el-select {
    .el-input {
      height: auto !important;
    }
  }
  .payment{
    margin-left: 17px;
  }
</style>
